/*自定义一个滑块组件用于指定了一个总数，在这个总数内调整每个元素值的大小，使其不容易溢出*/

function customSliderObj (option) {

    let obj = {}
    //重新配置option
    obj.resetOption = function (option){
        for(let key in obj.option){
            if(option[key]==undefined){
                option[key] = obj.option[key]
            }
        }
        obj.option = option
        obj.init(obj.option)
    }
    //重新配置ranges
    obj.resetRanges = function (ranges){
        obj.option['ranges'] = ranges
        obj.init(obj.option)
    }
    //加载渲染每一个sliderItem
    obj.appendItem = function (ele,ranges){
        $(ele).html('')
        $(ele + ' .jc-slider-box').attr('role','slider')
        $(ele + ' .jc-slider-box').attr('aria-label','滑块')
        $(ele + ' .jc-slider-box').attr('tabindex','0')
        $(ele).append(`<div class="jc-slider-box"></div>`)
        // let $style = $(`<style>.slider-item{position:absolute;top:-8px;width:16px;height:16px;border-radius:10px;background-color:#fff;border:2px solid #00ac66;line-height:16px;text-align:center;transition:transform .3s ease-in-out}.slider-item:not(.slider-item:nth-child(1)){cursor:crosshair}.slider-item-active{transform:scale(1.2)}.slider-item .slider-item-label{position:absolute;top:30px;left:-40px;width:100px;height:30px;background-color:rgba(0,0,0,0.5);line-height:30px;color:#fff;font-size:8px;border-radius:15px;padding:0 3px}</style>`)
        // $(ele).append($style)
        let sum = ranges.reduce((index,item)=>item.value+index,0)
        let cont = 0
        ranges.reduce((index,item)=>{
            if(index!==0){
                $(ele + ' .jc-slider-box').append(
                    `<div tabindex="0" class="jc-slider-item" style="left:${index/sum*100}%" data-index="${cont}">
                                <div class="jc-slider-item-label" style="${obj.option.labelShow?'display:flex':'display:none'}">
                                    <div class="js-slider-label-name">${' 名称：' + item.name}</div>
                                    <div class="js-slider-label-value">${' 权重：' + item.value}</div>
                                </div>
                            </div>`
                )
            }else{
                $(ele + ' .jc-slider-box').append(`<div class="jc-slider-item jc-first-item" style="left:0%" data-index="${cont}">
                                             <div class="jc-slider-item-label" style="${obj.option.labelShow?'display:flex':'display:none'}">
                                                <div class="js-slider-label-name">${' 名称：' + item.name}</div>
                                                <div class="js-slider-label-value">${' 权重：' + item.value}</div>
                                            </div>
                                        </div>`)
            }
            cont+=1
            return item.value+index
        },0)
    }
    //标签元素自动调整位置
    obj.autoLabelOption = function (e){
        let currentEle = e.currentTarget
        let prveEle = e.currentTarget.previousElementSibling
        let currentLabelEle = e.currentTarget.getElementsByClassName('jc-slider-item-label')[0]
        let prveLabelEle = e.currentTarget.previousElementSibling.getElementsByClassName('jc-slider-item-label')[0]
        let nextEle = e.currentTarget.nextElementSibling
        let w2 = prveLabelEle.offsetWidth/2
        if(nextEle){
            let nextLabelEle = e.currentTarget.nextElementSibling.getElementsByClassName('jc-slider-item-label')[0]
            if(currentEle.offsetLeft + w2 >= nextEle.offsetLeft - w2 ){
                if(nextLabelEle.className.indexOf('jc-slider-item-label-top')==-1){
                    currentLabelEle.classList.add('jc-slider-item-label-top')
                }else{
                    currentLabelEle.classList.remove('jc-slider-item-label-top')
                }
            }else{
                currentLabelEle.classList.remove('jc-slider-item-label-top')
                if(currentEle.offsetLeft - w2 <= prveEle.offsetLeft + w2){
                    prveLabelEle.classList.add('jc-slider-item-label-top')
                }else{
                    prveLabelEle.classList.remove('jc-slider-item-label-top')
                }
            }
        }else{
            if(currentEle.offsetLeft - w2 <= prveEle.offsetLeft + w2){
                if(prveLabelEle.className.indexOf('jc-slider-item-label-top')==-1){
                    currentLabelEle.classList.add('jc-slider-item-label-top')
                }else{
                    currentLabelEle.classList.remove('jc-slider-item-label-top')
                }
            }else{
                currentLabelEle.classList.remove('jc-slider-item-label-top')
            }
        }
    }
    //对元素进行初始化
    obj.init = function (option){

        let defaultOption = {
            ele:'#slider',
            ranges:[ {name:'奖品1',value:18},
                {name:'奖品2',value:10},
                {name:'奖品3',value:20},
                {name:'奖品4',value:40},
                {name:'奖品5',value:10},
                {name:'奖品6',value:20}],
            moveCallback:function (res){}
        }
        for(let key in defaultOption){
            if(option[key]==undefined){
                option[key] = defaultOption[key]
            }
        }
        obj.option = option
        let ele = obj.option.ele
        let moveCallback = obj.option.moveCallback
        obj.appendItem(ele,obj.option.ranges)
        let eventState = 0
        let diffX
        let self = this
        let jcSliderItemReg = /^jc-slider-item$/
        //item在激活的状态
        let sliderItemChangeShow = function (e){

            e.currentTarget.style.zIndex = 10
            e.currentTarget.classList.add('jc-slider-item-active')
            e.currentTarget.focus()
            if(!obj.option.labelShow)
                e.currentTarget.children[0].style.display='flex'

        }
        //item在失活的状态
        let sliderItemChangeHide = function (e){
            e.currentTarget.style.zIndex = 5
            e.currentTarget.classList.remove('jc-slider-item-active')
            if(!obj.option.labelShow){
                e.currentTarget.children[0].style.display='none'
            }
        }
        //元素移动后值的计算以及前面label的显示和输入结果的较正。核心方法
        let moveValueChange = function (e){
            //当前激活元素的上一个兄弟元素
            let prevElement = e.currentTarget.previousElementSibling
            //当前激活元素上一个兄弟元素的值的元素
            let prevElementValueEle = e.currentTarget.previousElementSibling.children[0].children[1]
            //当前激活元素的下一个兄弟元素
            let nextElement = e.currentTarget.nextElementSibling
            //当前元素
            let currElement = e.currentTarget
            //当前元素的值的元素
            let currElementValueEle = e.currentTarget.children[0].children[1]
            //当前ranges的值的求和
            let sum = obj.option.ranges.reduce((index,item)=>item.value+index,0)
            let ew = $(ele)[0].clientWidth
            let reg = /权重：\d+|权重：-\d+/
            let currentValue= Math.ceil((ew - currElement.offsetLeft) / ew * sum)
            if(nextElement)
                currentValue= Math.ceil((nextElement.offsetLeft - currElement.offsetLeft) / ew * sum)
            currElementValueEle.innerText = currElementValueEle.innerText.replace(reg,'权重：'+currentValue)
            let prveVal = Math.floor((currElement.offsetLeft - prevElement.offsetLeft) / ew * sum)
            prevElementValueEle.innerText =  prevElementValueEle.innerText.replace(reg,'权重：'+prveVal)
            obj.option.ranges[currElement.dataset.index]['value'] = currentValue
            obj.option.ranges[prevElement.dataset.index]['value'] = prveVal
            let cSum = obj.option.ranges.reduce((prveSum,item)=>prveSum+item.value,0)
            //精度补偿处理
            if(cSum !== sum){
                let chaZhi = sum - cSum
                if(currentValue.offsetLeft == prevElement.offsetLeft && chaZhi == 1){
                    obj.option.ranges[prevElement.dataset.index]['value'] = 0
                    obj.option.ranges[currElement.dataset.index]['value'] += 1
                    currElementValueEle.innerText = currElementValueEle.innerText.replace(reg,'权重：' + obj.option.ranges[currElement.dataset.index]['value']);
                }else if(currentValue.offsetLeft == prevElement.offsetLeft && chaZhi < 0){
                    obj.option.ranges[prevElement.dataset.index]['value'] = 0
                    obj.option.ranges[currElement.dataset.index]['value'] += chaZhi
                    currElementValueEle.innerText = currElementValueEle.innerText.replace(reg,'权重：' + obj.option.ranges[currElement.dataset.index]['value']);
                }else if(currentValue.offsetLeft == 2 && prevElement.offsetLeft == 0 && chaZhi < 0){
                    obj.option.ranges[prevElement.dataset.index]['value'] = 0
                    obj.option.ranges[currElement.dataset.index]['value'] += 1
                    currElementValueEle.innerText = currElementValueEle.innerText.replace(reg,'权重：' + obj.option.ranges[currElement.dataset.index]['value']);
                }else{
                    obj.option.ranges[prevElement.dataset.index]['value']+=chaZhi
                }
                prevElementValueEle.innerText = prevElementValueEle.innerText.replace(reg,'权重：' + obj.option.ranges[prevElement.dataset.index]['value']);
            }
        }


        $(ele + ' .jc-slider-box').unbind('mousedown').unbind('mousemove').unbind('mouseup').unbind('mouseout').unbind('mouseover')

        //事件处理阶段
        let jcSliderBox = $(ele + ' .jc-slider-box')
        //鼠标向下事件
        jcSliderBox.on('mousedown','.jc-slider-item:not(.jc-first-item)',function (e){
            diffX = e.clientX - e.currentTarget.offsetLeft
            eventState = 1
            sliderItemChangeShow(e)
        })
        //鼠标移动事件
        jcSliderBox.on('mousemove','.jc-slider-item:not(.jc-first-item)',function (e){
            e.preventDefault()
            e.stopPropagation()
            if(eventState){
                //当前激活元素的上一个兄弟元素
                let prevElement = e.currentTarget.previousElementSibling
                //当前激活元素的下一个兄弟元素
                let nextElement = e.currentTarget.nextElementSibling
                //当前元素
                let currElement = e.currentTarget
                let moveX = e.clientX - diffX
                if(moveX < 0){
                    return
                }
                if(moveX > $(ele)[0].clientWidth){
                    return
                }
                let ew = $(ele)[0].clientWidth
                if(moveX < prevElement.offsetLeft){
                    return
                }
                if(nextElement)
                    if(nextElement.offsetLeft < moveX){
                        return
                    }
                //给当前元素的left，赋上值
                currElement.style.left = moveX + 'px'
                moveValueChange(e)
                moveCallback.call($(ele)[0],self.option.ranges)
            }
            sliderItemChangeShow(e)
            obj.autoLabelOption(e)
        })
        //鼠标向上事件
        jcSliderBox.on('mouseup','.jc-slider-item:not(.jc-first-item)',function (e){
            eventState = 0
            sliderItemChangeHide(e)

        })
        //鼠标离开事件
        jcSliderBox.on('mouseout','.jc-slider-item:not(.jc-first-item)',function (e){
            eventState = 0
            sliderItemChangeHide(e)

        })
        //鼠标失活事件
        jcSliderBox.on('blur','.jc-slider-item:not(.jc-first-item)',function (e){
            eventState = 0
            sliderItemChangeHide(e)

        })
        //每一个sliderItem的事件处理
        if(!obj.option.labelShow){
            jcSliderBox.on('mousemove','.jc-first-item',function (e){
                sliderItemChangeShow(e)
            })
            jcSliderBox.on('mousedown','.jc-first-item',function (e){
                sliderItemChangeShow(e)
            })
            jcSliderBox.on('mouseout','.jc-first-item',function (e){
                sliderItemChangeHide(e)
            })
            jcSliderBox.on('mouseup','.jc-first-item',function (e){
                sliderItemChangeHide(e)
            })
        }

        let rangesSum = obj.option.ranges.reduce((prveSum,item)=>item.value+prveSum,0)
        //键盘移动一次元素需要增加的left值 相当于用每个ranges值进行一次逆运算。
        let proportion = 1 / rangesSum * $(ele)[0].clientWidth
        //每敲击一次键盘的迭代值
        let Iterative = 0
        //键盘微调事件处理
        jcSliderBox.on('keydown','.jc-slider-item',function (e){
            let currElement = e.currentTarget
            let nextElement = e.currentTarget.nextElementSibling
            let prveElement = e.currentTarget.previousElementSibling
            let currIndex = currElement.dataset.index
            let prveIndex = prveElement.dataset.index
            let ew = $(ele).clientWidth
            let offsetVal = 0

            if(e.keyCode === 9){ //tab选中
                $(currElement).mouseup()
            }else if(e.keyCode === 37){ //向左微调
                if(obj.option.ranges[prveIndex]['value']==0){
                    Iterative=0
                    return
                }
                Iterative -= proportion
                obj.option.ranges[currIndex]['value'] += 1
                obj.option.ranges[prveIndex]['value'] -= 1
            }else if(e.keyCode === 39){ //向右微调
                if(obj.option.ranges[currIndex]['value']==0){
                    Iterative=0
                    return
                }
                Iterative += proportion
                obj.option.ranges[currIndex]['value'] -= 1
                obj.option.ranges[prveIndex]['value'] += 1
            }

            if(e.keyCode === 37 || e.keyCode === 39){ //向左微调
                if(obj.option.ranges[currIndex]['value']<0){
                    obj.option.ranges[currIndex]['value']=0
                    Iterative=0
                    return
                }
                if(obj.option.ranges[prveIndex]['value']<0){
                    obj.option.ranges[prveIndex]['value']=0
                    Iterative=0
                    return
                }
                currElement.children[0].children[1].innerText = '权重：' + obj.option.ranges[currIndex].value
                prveElement.children[0].children[1].innerText = '权重：' + obj.option.ranges[prveIndex].value
                if(proportion>=1){
                    //迭代器累计到整数值时让元素进行移动
                    offsetVal = currElement.offsetLeft + Iterative
                    currElement.style.left = offsetVal + 'px'
                    Iterative = 0
                    moveCallback.call($(ele)[0],obj.option.ranges)
                }else{
                    if(Math.ceil(Iterative,2) == -1 || Math.floor(Iterative,2) == 1){
                        //迭代器累计到整数值时让元素进行移动
                        offsetVal = currElement.offsetLeft + Math.floor(Iterative,2)
                        currElement.style.left = offsetVal + 'px'
                        Iterative = 0
                        moveCallback.call($(ele)[0],obj.option.ranges)
                    }
                }
            }
        })

        jcSliderBox.on('keyup','.jc-slider-item',function (e){
            let currElement = e.currentTarget
            let nextElement = e.currentTarget.nextElementSibling
            let prveElement = e.currentTarget.previousElementSibling
            if(e.keyCode ===9){ //tab选中
                $(e.currentTarget).mousedown()
            }else if(e.keyCode === 37){ //向左微调

            }else if(e.keyCode === 39){ //向右微调
            }
            obj.autoLabelOption(e)
        })


    }
    obj.init(option)
    return obj
}


//自定义一个播放器的滑块组件
function customPlaySlider(option) {

    let defaultOptio = {
        value:0, //初始化值
        maxValue:100, //最大值
        minValue:0, //最小值
        controlColor:'#ED4242',
        sliderColor:'#E6E6E6',
        cacheColor:'#D1D1D1',
        ele:'#playSliderBox', //默认元素Id
        moveStartEvent:function (val){}, //开始移动事件
        moveEvent:function (val){}, //移动中事件
        moveEnd:function (val){}, //移动停止事件
    }
    let obj = {}
    Object.keys(defaultOptio).forEach(key=>{
        if(option[key]==undefined){
            option[key] = defaultOptio[key]
        }
    })
    obj.option = option
    obj.setValue = function(value,cacheVal=0){
        let sliderWidth = $(obj.option.ele)[0].offsetWidth
        let minValue = obj.option.minValue
        let maxValue = obj.option.maxValue
        if(value<minValue)value=minValue
        if(value>maxValue)value=maxValue
        let FIXX = sliderWidth * (value / maxValue - minValue)
        let CACHEVAL = sliderWidth * (cacheVal / maxValue - minValue)
        $('#jcPlayerSliderControl').css({left:FIXX + 'px'})
        $('#jcPlayerSliderProgressbar').attr('aria-valuenow',value).css({backgroundImage:'linear-gradient(to right,' + obj.option.controlColor + ' ' + FIXX + 'px,'+obj.option.cacheColor+' 0px,'+obj.option.cacheColor+' '+CACHEVAL+'px,' + obj.option.sliderColor + ' 0px)'})

    }
    obj.getValue = function(){
        let sliderWidth = $(obj.option.ele)[0].offsetWidth
        let minValue = obj.option.minValue
        let maxValue = obj.option.maxValue
        let bfb = $('#jcPlayerSliderControl')[0].offsetLeft / sliderWidth
        let val = Math.ceil((maxValue - minValue) * bfb) + minValue
        return val
    }
    obj.init = function (option) {
        let ele = $(option.ele)
        let value = option.value
        let minValue = option.minValue
        let maxValue = option.maxValue
        if(value<minValue)value=minValue
        if(value>maxValue)value=maxValue
        let sliderControlClass ='jc-slider-control'
        let progressbarClass = 'jc-play-slider'
        let sliderWidth = $(ele)[0].offsetWidth
        let sliderLeft = $(ele)[0].offsetLeft
        let FIXX = 0
        ele.html('')
        $html = `<div id="jcPlayerSliderProgressbar" style="background-color:${obj.option.sliderColor};background-image: linear-gradient(to right,${obj.option.controlColor} 0%,${obj.option.sliderColor} 0%);"  tabindex="0" role="progressbar" aria-valuenow="${value}" aria-valuemax="${maxValue}" aria-valuemin="${minValue}" class="${progressbarClass}">
                            <div tabindex="0" id="jcPlayerSliderControl" class="${sliderControlClass}" style="background-color:${obj.option.controlColor}"></div>
                        </div>`
        ele.html($html)
        FIXX = Math.ceil(value / (maxValue - minValue) * sliderWidth)
        $('#jcPlayerSliderControl').css({left:FIXX+'px'})
        outVal()
        $('#jcPlayerSliderProgressbar').on('click',function (e){

            if(!$('#jcPlayerSliderControl').is(e.target) && $('#jcPlayerSliderControl').has(e.target).length === 0 && $('#jcPlayerSliderControl').length){
                obj.option.moveStartEvent.call(this,outVal())
                FIXX = Math.abs(sliderLeft - e.clientX)
                if(FIXX < 0)FIXX = 0;if(FIXX > sliderWidth)FIXX = sliderWidth
                obj.option.moveEnd.call(this,outVal())
            }
        })
        $('#jcPlayerSliderControl').unbind('mousedown').unbind('touchstart')
        $('#jcPlayerSliderControl').bind({
            'mousedown':function (e){
                appMoveing(e)
            },
            'touchstart':function (e){
                appMoveing(e)
            },
            'keydown':function (e){
                move(e)
            },
            'keyup':function (e){
                up(e)
            }
        })
        //添加移动事件用的遮罩层
        function appMoveing(e){

            if(e.type == 'touchstart'){
                $(e.currentTarget).on('touchmove',move)
                $(e.currentTarget).on('touchend',up)
            }else{
                let moveing = `<div class="jc-moveing"></div>`
                $('body').append(moveing)
                $('.jc-moveing').on('mousemove',move)
                $('.jc-moveing').on('mouseup',up)
            }
            obj.option.moveStartEvent.call(this,outVal())
        }
        function move(e){
            let clientX = 0
            if(e.type == 'touchmove'){
                clientX = e.clientX || e.originalEvent.changedTouches[0].clientX
                FIXX = Math.abs(sliderLeft - clientX)
            }else if(e.type=='mousemove'){
                clientX = e.clientX
                FIXX = Math.abs(sliderLeft - clientX)
            }else if(e.type=='keydown'){
                obj.option.moveStartEvent.call(this,outVal())
                clientX = sliderLeft+10
                if(e.keyCode=='39'){
                    FIXX = e.currentTarget.offsetLeft + 1
                }else if(e.keyCode=='37'){
                    FIXX = e.currentTarget.offsetLeft - 1
                }
            }
            if(FIXX < 0)FIXX = 0;if(FIXX > sliderWidth)FIXX = sliderWidth
            if(clientX < sliderLeft)FIXX = 0;if(clientX > sliderWidth+sliderLeft)FIXX = sliderWidth
            $('#jcPlayerSliderControl')[0].classList.add('slider-control-active')
            obj.option.moveEvent.call(this,outVal())
        }
        function up (e){
            $('.jc-moveing').remove()
            $('#jcPlayerSliderControl')[0].classList.remove('slider-control-active')
            obj.option.moveEnd.call(window,outVal())
        }
        //计算输出值
        function outVal(){
            let minValue = obj.option.minValue
            let maxValue = obj.option.maxValue
            let bfb = FIXX / sliderWidth
            let val = Math.ceil((maxValue - minValue) * bfb) + minValue
            $('#jcPlayerSliderControl').css({left:FIXX + 'px'})
            $('#jcPlayerSliderProgressbar').attr('aria-valuenow',val).css({backgroundImage:'linear-gradient(to right,' + obj.option.controlColor + ' ' + FIXX + 'px,rgba(0,0,0,0.5) 0%,' + obj.option.sliderColor + ' 0px)'})
            return val
        }
    }
    obj.init(obj.option)
    return obj
}



//自定义一个播放器组件

function customPlayBox(option){
    let audio = document.createElement('audio')
    let defaultOption = {
        ele:'#playBox', //绑定元素
        url:'', //绑定要播放的链接
        controlColor: '#97BA7F', //设置进度控制小球的颜色
        sliderColor: '#E6E6E6', //设置进度条背景颜色
        cacheColor:'#D1D1D1',//设置缓存进度条的颜色
        textColor:'#fff',//时间文字默认颜色
        playIconClass:'jc-play-btn',//播放和暂停ICON的颜色
        pauseIconClass:'jc-pause-btn',//播放和暂停ICON的颜色
        animate:true,//暂停时收起进度条 动画暂时不做
        onendedCall:function (){},//播放完成回调
        onloadedmetadataCall:function (){},//音频准备完成后回调
    }
    Object.keys(defaultOption).forEach(key=>{
        if(option[key]==undefined){
            option[key] = defaultOption[key]
        }
    })
    audio.option = option
    audio.onloadedmetadataCall = function (){} //给audio加一下当加载准备完成后的回调
    audio.init = function init(option){
        let ele = option.ele
        $(ele).html('')
        $(ele).append(`<div class="jc-play-progress">
                                <div class="jc-play-nowTime" style="color:${audio.option.textColor}" aria-label="当前音频播放时间" tabindex="0" aria-live="00:00:00">00:00:00</div>
                                <div id="playSlider-box"></div>
                                <div class="jc-play-endTime" style="color:${audio.option.textColor}" aria-label="当前音频播放时间总长" tabindex="0"  aria-live="00:00:00">00:00:00</div>
                                <div id="jc-play-btn" tabindex="0" role="button" aria-label="播放和暂停按钮" class="jc-play-play-or-pause-icon ${audio.option.playIconClass}"></div>
                            </div>`)
        if(option.url !== ""){
            audio.src  = option.url
        }
        $('#jc-play-btn').unbind('click')
        $('.jc-prevplay-btn').unbind('click')
        $('.jc-nextplay-btn').unbind('click')
        $('#jc-play-btn').bind({
            click:function (e){
                if(audio.paused){
                    audio.play()
                }else{
                    audio.pause()
                }
            },
            keypress:function (e){
                if(e.keyCode==13){
                    if(audio.paused){
                        audio.play()
                    }else{
                        audio.pause()
                    }
                }
            }
        })
        $('.jc-prevplay-btn').bind({
            click:function (e){
            }
        })
        $('.jc-nextplay-btn').bind({
            click:function (e){
            }
        })
        $(audio).bind({
            'play':function (){
                playIcon()
            },
            'playing':function (){
                playIcon()
            },
            'pause':function (){
                pauseIcon()

            },
            'error':function (){
                erroIcon()
            },
            'timeupdate':function (){
                let timeRanges = audio.buffered;
                let bufferPercent
                try{
                    timeBuffered = timeRanges.end(timeRanges.length - 1);
                    //缓存进度
                    bufferPercent =Math.ceil(timeBuffered / audio.duration * 100);
                }catch(err){
                    bufferPercent = 0
                }
                //播放进度
                let currentTime = Math.ceil(audio.currentTime / audio.duration * 100);
                nowTime(audio.currentTime)
                playSlider.setValue(currentTime,bufferPercent)
            },
            'ended':function (){
                playSlider.setValue(0)
                pauseIcon()
                nowTime(0)
                option.onendedCall.call(audio)
            },
            'waiting':function (){
                pauseIcon()
            },
            'loadedmetadata':function (){
                nowTime(0)
                audio.onloadedmetadataCall.call(audio)
                option.onloadedmetadataCall.call(audio)
                endTime(audio.duration)
            },

        })
    }
    audio.init(option)
    let playSlider = customPlaySlider({
        ele:'#playSlider-box',
        minValue:0,
        maxValue:100,
        controlColor: audio.option.controlColor,
        sliderColor: audio.option.sliderColor,
        cacheColor:audio.option.cacheColor,
        moveStartEvent:function (val){
            //移动之前记录一下当前的播放状态
            this.audioMovePaused = audio.paused
            audio.pause()
        },
        moveEvent:function (val){
        },
        moveEnd:function (val){
            let currentTime = audio.duration * (val / 100)
            audio.currentTime = currentTime
            nowTime(audio.duration * (val / 100))
            if(this.audioMovePaused){
                audio.pause()
            }else{
                audio.play()
            }
        }
    })
    /**
     * 通过外部方法改变audio的src对象 直接调用audio.src的话会报错
     * @param src 要重置的音频
     * @param nextPlay 是否切换过来开始播放 0 代表不播放 1代表播放
     */
    audio.resetSrc = function (src,nextPlay=0){
        audio.pause()
        audio.src = src
        loadingIcon()
        endTime(0);nowTime(0)
        playSlider.setValue(0,0)
        audio.onloadedmetadataCall = function (){
            if(nextPlay==1){
                audio.play()
                playIcon()
            }else{
                pauseIcon()
            }
        }
    }

    //将分钟数转化为时分秒
    function formatSeconds(value) {
        var theTime = parseInt(value);// 秒
        var theTime1 = 0;// 分
        var theTime2 = 0;// 小时
        if (theTime > 60) {
            theTime1 = parseInt(theTime / 60);
            theTime = parseInt(theTime % 60);
            if (theTime1 > 60) {
                theTime2 = parseInt(theTime1 / 60);
                theTime1 = parseInt(theTime1 % 60);
            }
        }
        var result = "" + parseInt(theTime);
        if(result < 10){
            result = '0' + result;
        }
        if (theTime1 > 0) {
            result = "" + parseInt(theTime1) + ":" + result;
            if(theTime1 < 10){
                result = '0' + result;
            }
        }else{
            result = '00:' + result;
        }
        if (theTime2 > 0) {
            result = "" + parseInt(theTime2) + ":" + result;
            if(theTime2 < 10){
                result = '0' + result;
            }
        }else{
            result = '00:' + result;
        }
        return result;
    }
    //播放状态图标
    function playIcon(){
        playIconChange(audio.option.pauseIconClass)
    }
    //暂停状态图标
    function pauseIcon(){
        playIconChange(audio.option.playIconClass)
    }
    //等待音频加载
    function loadingIcon(){

        playIconChange('jc-pause-loading')

    }
    //音频播放出错
    function erroIcon(){
        playIconChange('jc-erro-btn')
    }
    //播放按钮状态切换功能
    /**
     * 要改变的状态的class名称
     * @param className
     */
    function playIconChange(className) {
        const PLAY_BTN = $('#jc-play-btn')[0]
        const stateClassNames = ['jc-erro-btn',audio.option.pauseIconClass,'jc-pause-loading',audio.option.playIconClass]
        $(stateClassNames).each(index=>{
            let stateClassName = stateClassNames[index]
            if(stateClassName.indexOf(className)!==-1){
                PLAY_BTN.classList.add(stateClassName)
            }else{
                PLAY_BTN.classList.remove(stateClassName)
            }
        })
    }
    //播放时当前时间元素渲染更新
    function nowTime(second){
        $('.jc-play-nowTime').text(formatSeconds(second))
        $('.jc-play-nowTime').attr('aria-live',formatSeconds(second))
    }
    //播放时当总时间长元素渲染更新
    function endTime(second){
        $('.jc-play-endTime').text(formatSeconds(second))
        $('.jc-play-endTime').attr('aria-live',formatSeconds(second))
    }

    return audio

}


//获取链接中带的query传递的参数参数
function getcanshu(){

    let canshu = window.location.search.replace("?","")

    let arr = canshu.split("&")

    let canshuobj = {}

    for(var i =  0  ; i < arr.length ; i++){

        var c = arr[i].split("=")

        canshuobj[c[0]] = c[1]

    }

    return canshuobj
}

//日期格式化函数
function dateFormat(date,format){
    var o = {
        "M+" : date.getMonth()+1, //month
        "d+" : date.getDate(),    //day
        "h+" : date.getHours(),   //hour
        "m+" : date.getMinutes(), //minute
        "s+" : date.getSeconds(), //second
        "q+" : Math.floor((date.getMonth()+3)/3),  //quarter
        "S" : date.getMilliseconds() //millisecond
    }
    if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
        (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)if(new RegExp("("+ k +")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length==1 ? o[k] :
                ("00"+ o[k]).substr((""+ o[k]).length));
    return format;
}

//判断是否是微信手机端浏览器
function iswxBrower(){
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {//判断是否是移动设备打开。browser代码在下面
        var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true
        }else{
            return false
        }
    }else{
        return false
    }
}
